<template>
  <div class="business-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>营业管理</h1>
        <p>管理营业状态、推广曝光和账户余额</p>
      </div>
      <div class="header-actions">
        <el-button
          :type="businessStatus.isOpen ? 'danger' : 'success'"
          @click="toggleBusinessStatus"
          :loading="statusChanging"
        >
          {{ businessStatus.isOpen ? '停止营业' : '开始营业' }}
        </el-button>
      </div>
    </div>

    <!-- 营业状态概览 -->
    <el-row :gutter="20" class="status-section">
      <el-col :span="8">
        <el-card class="stat-card status">
          <div class="stat-content">
            <div class="stat-icon" :class="businessStatus.isOpen ? 'open' : 'closed'">
              <el-icon><component :is="businessStatus.isOpen ? 'CircleCheck' : 'CircleClose'" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ businessStatus.isOpen ? '营业中' : '已打烊' }}</div>
              <div class="stat-label">{{ businessStatus.isOpen ? '正在接受新订单' : '暂停接受新订单' }}</div>
              <div class="stat-time">营业时间：{{ businessStatus.openTime }} - {{ businessStatus.closeTime }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="stat-card performance">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ performance.rating }}分</div>
              <div class="stat-label">服务评分</div>
              <div class="stat-desc">
                响应{{ performance.responseTime }}分钟 | 退款率{{ performance.refundRate }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="stat-card balance">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(accountBalance) }}</div>
              <div class="stat-label">账户余额</div>
              <div class="stat-actions">
                <el-button size="small" type="primary" @click="showRechargeDialog">充值</el-button>
                <el-button size="small" @click="viewTransactions">明细</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 推广管理 -->
    <el-card class="promotion-card">
      <template #header>
        <div class="card-header">
          <span>推广曝光管理</span>
          <el-tag :type="getExposureLevelType(promotionStats.exposureLevel)">
            {{ getExposureLevelText(promotionStats.exposureLevel) }}
          </el-tag>
        </div>
      </template>

      <!-- 推广数据统计 -->
      <el-row :gutter="20" class="promotion-stats">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ promotionStats.currentExposure }}</div>
            <div class="stat-label">当前小时曝光</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">+{{ promotionStats.orderIncrease }}</div>
            <div class="stat-label">订单增长</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">+{{ promotionStats.consultIncrease }}</div>
            <div class="stat-label">咨询增长</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ promotionStats.avgRating }}</div>
            <div class="stat-label">综合评分</div>
          </div>
        </el-col>
      </el-row>

      <!-- 智能调节状态 -->
      <div class="auto-adjustment">
        <div class="adjustment-header">
          <span>智能曝光调节</span>
          <el-switch
            v-model="promotionStats.autoAdjusting"
            @change="toggleAutoAdjustmentSetting"
            active-text="开启"
            inactive-text="关闭"
          />
        </div>
        <div class="adjustment-info">
          <el-alert
            v-if="promotionStats.needsApproval"
            title="曝光量已达到高级别，需要后端审核才能进入更大量级曝光"
            type="warning"
            :closable="false"
            show-icon
          />
          <el-alert
            v-else-if="promotionStats.autoAdjusting"
            title="系统正在根据订单量、咨询量、评价等数据自动调节曝光度"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <!-- 推广方案 -->
      <div class="promotion-plans">
        <el-row :gutter="20" v-if="promotionPlans && promotionPlans.length > 0">
          <el-col :span="8" v-for="plan in promotionPlans" :key="plan?.id || Math.random()">
            <div class="plan-item" :class="{ active: plan?.isActive }">
              <div class="plan-header">
                <h4>{{ plan?.name || '未知方案' }}</h4>
                <div class="plan-price">
                  <span class="price">¥{{ plan?.price || 0 }}</span>
                  <span class="unit">/{{ plan?.unit || '天' }}</span>
                </div>
              </div>
              <div class="plan-description">
                <p>{{ plan?.description || '暂无描述' }}</p>
              </div>
              <div class="plan-actions">
                <el-button
                  v-if="!plan?.isActive"
                  type="primary"
                  @click="handlePurchasePromotion(plan)"
                  :loading="plan?.purchasing"
                  style="width: 100%;"
                >
                  开启推广
                </el-button>
                <el-button v-else type="success" disabled style="width: 100%;">
                  推广中
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <div v-else class="no-plans">
          <p>暂无推广方案</p>
        </div>
      </div>
    </el-card>

    <!-- 风控提醒 -->
    <el-card class="risk-card" v-if="riskAlerts.length > 0">
      <template #header>
        <div class="card-header">
          <span>风控提醒</span>
          <el-tag type="warning">需要关注</el-tag>
        </div>
      </template>
      <div class="risk-content">
        <div v-for="alert in riskAlerts" :key="alert.id" class="risk-item">
          <el-icon class="risk-icon" :class="alert.level"><Warning /></el-icon>
          <div class="risk-info">
            <div class="risk-title">{{ alert.title }}</div>
            <div class="risk-desc">{{ alert.description }}</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 充值对话框 -->
    <el-dialog
      v-model="rechargeDialogVisible"
      :title="paymentStep === 'form' ? '账户充值' : '完成支付'"
      width="600px"
      @close="resetRechargeForm"
    >
      <!-- 充值表单 -->
      <div v-if="paymentStep === 'form'" class="recharge-content">
        <div class="current-balance">
          <span>当前余额：</span>
          <span class="balance">¥{{ accountBalance.toFixed(2) }}</span>
        </div>

        <el-form :model="rechargeForm" label-width="100px">
          <el-form-item label="充值方式">
            <el-radio-group v-model="rechargeForm.amountType">
              <el-radio label="quick">快速选择</el-radio>
              <el-radio label="custom">自定义金额</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="rechargeForm.amountType === 'quick'" label="快速选择">
            <div class="quick-amounts">
              <el-button
                v-for="amount in quickAmounts"
                :key="amount"
                @click="rechargeForm.amount = amount"
                :type="rechargeForm.amount === amount ? 'primary' : 'default'"
                size="small"
              >
                ¥{{ amount }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item v-if="rechargeForm.amountType === 'custom'" label="自定义金额">
            <el-input-number
              v-model="rechargeForm.amount"
              :min="1"
              :max="50000"
              :precision="2"
              controls-position="right"
              style="width: 100%;"
              placeholder="请输入充值金额"
            />
            <div class="custom-tips">
              <p>• 最低充值金额：¥1</p>
              <p>• 最高充值金额：¥50,000</p>
              <p>• 支持小数点后两位</p>
            </div>
          </el-form-item>
          
          <el-form-item label="支付方式">
            <el-radio-group v-model="rechargeForm.paymentMethod">
              <el-radio label="wechat">
                <el-icon><ChatDotRound /></el-icon>
                微信支付
              </el-radio>
              <el-radio label="alipay">
                <el-icon><Wallet /></el-icon>
                支付宝
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <div class="recharge-summary">
          <div class="summary-item">
            <span>充值金额：</span>
            <span class="amount">¥{{ rechargeForm.amount.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>充值后余额：</span>
            <span class="amount">¥{{ (accountBalance + rechargeForm.amount).toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 支付页面 -->
      <div v-if="paymentStep === 'payment'" class="payment-section">
        <div class="payment-header">
          <div class="payment-info">
            <h3>账户充值</h3>
            <p class="amount">充值金额：¥{{ currentRechargeOrder.amount }}</p>
            <p class="order-id">订单号：{{ currentRechargeOrder.orderId }}</p>
          </div>
          <div class="payment-timer">
            <el-icon><Timer /></el-icon>
            <span>{{ formatTime(rechargeRemainingTime) }}</span>
          </div>
        </div>

        <!-- 支付宝支付 -->
        <div v-if="rechargePaymentInfo.type === 'alipay'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#1677ff"><Money /></el-icon>
            <span>支付宝支付</span>
          </div>
          <div class="qr-section">
            <div class="qr-code">
              <img :src="generateQRCode(rechargePaymentInfo.qrCode)" alt="支付宝二维码" />
            </div>
            <div class="qr-instructions">
              <p>请使用支付宝扫描二维码完成支付</p>
              <p>支付完成后系统将自动确认到账</p>
              <p>请勿关闭此页面</p>
            </div>
          </div>
        </div>

        <!-- 微信支付 -->
        <div v-if="rechargePaymentInfo.type === 'wechat'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#07c160"><ChatDotRound /></el-icon>
            <span>微信支付</span>
          </div>
          <div class="qr-section">
            <div class="qr-code">
              <img :src="generateQRCode(rechargePaymentInfo.qrCode)" alt="微信支付二维码" />
            </div>
            <div class="qr-instructions">
              <p>请使用微信扫描二维码完成支付</p>
              <p>支付完成后系统将自动确认到账</p>
              <p>请勿关闭此页面</p>
            </div>
          </div>
        </div>

        <!-- 银行卡支付 -->
        <div v-if="rechargePaymentInfo.type === 'bank'" class="payment-content">
          <div class="payment-method-header">
            <el-icon size="32" color="#f56c6c"><CreditCard /></el-icon>
            <span>银行卡支付</span>
          </div>
          <div class="bank-section">
            <p class="bank-instruction">点击下方按钮跳转到银行支付页面</p>
            <p class="bank-instruction">支付完成后系统将自动确认到账</p>
            <div class="payment-actions">
              <el-button type="primary" size="large" @click="openRechargeBank">
                前往银行支付页面
              </el-button>
            </div>
          </div>
        </div>

        <!-- 支付状态检查 -->
        <div v-if="checkingRechargePayment" class="payment-status">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在确认支付状态...</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRechargePayment">
            {{ paymentStep === 'form' ? '取消' : '取消支付' }}
          </el-button>
          <el-button
            v-if="paymentStep === 'form'"
            type="primary"
            @click="processRecharge"
            :loading="rechargeProcessing"
            :disabled="rechargeForm.amount < 1"
          >
            确认充值
          </el-button>
          <el-button
            v-if="paymentStep === 'payment'"
            type="text"
            @click="refreshRechargePaymentStatus"
          >
            刷新状态
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  CircleCheck,
  CircleClose,
  Check,
  Warning,
  Wallet,
  List,
  ChatDotRound,
  Star,
  Money,
  CreditCard,
  Timer,
  Loading
} from '@element-plus/icons-vue'
import {
  getBusinessStatus,
  updateBusinessStatus,
  getBusinessHours,
  updateBusinessHours,
  getPerformanceData,
  getAccountBalance,
  rechargeAccount,
  getTransactionHistory,
  getPromotionStats,
  getPromotionPlans,
  purchasePromotion,
  stopPromotion,
  toggleAutoAdjustment,
  getRiskAlerts,
  markRiskAlertRead,
  getBusinessSettings,
  updateBusinessSettings,
  BUSINESS_STATUS,
  BUSINESS_STATUS_TEXT,
  BUSINESS_STATUS_COLOR,
  PROMOTION_LEVELS,
  PROMOTION_LEVEL_TEXT,
  PROMOTION_LEVEL_COLOR,
  PAYMENT_METHODS,
  PAYMENT_METHOD_TEXT,
  getPromotionLevelType,
  getPromotionLevelText,
  getRiskLevelType,
  getRiskLevelText,
  getScoreLevel,
  getResponseTimeLevel,
  getRefundRateLevel
} from '@/api/business'

const router = useRouter()

// 营业状态
const businessStatus = reactive({
  isOpen: false,
  openTime: '08:00',
  closeTime: '22:00',
  status: BUSINESS_STATUS.CLOSED
})

const statusChanging = ref(false)

// 服务表现数据
const performance = reactive({
  rating: 0,
  responseTime: 0,
  refundRate: 0,
  badReviewRate: 0
})

// 智能推广计划
const promotionPlans = ref([])

// 推广数据统计
const promotionStats = reactive({
  currentExposure: 0, // 当前小时曝光量
  totalExposure: 0, // 总曝光量
  orderIncrease: 0, // 订单增长数
  consultIncrease: 0, // 咨询增长数
  avgRating: 0, // 平均评分
  exposureLevel: 'low', // 曝光等级: low, medium, high, super
  needsApproval: false, // 是否需要审核
  autoAdjusting: false // 是否自动调节
})

// 账户余额
const accountBalance = ref(0)

// 充值相关
const rechargeDialogVisible = ref(false)
const rechargeProcessing = ref(false)
const rechargeForm = reactive({
  amount: 100,
  amountType: 'quick', // quick: 快速选择, custom: 自定义
  paymentMethod: 'wechat'
})

// 支付相关状态
const paymentStep = ref('form') // 'form' | 'payment'
const currentRechargeOrder = ref(null)
const rechargePaymentInfo = ref(null)
const checkingRechargePayment = ref(false)
const rechargeRemainingTime = ref(0)
const rechargePaymentTimer = ref(null)

const quickAmounts = [50, 100, 200, 500, 1000, 2000]

// 推广选择
const selectedPromotion = ref(null)

// 风控提醒
const riskAlerts = ref([])

// 获取营业状态数据
const getBusinessStatusData = async () => {
  try {
    const response = await getBusinessStatus()
    if (response.code === 200) {
      const data = response.data
      businessStatus.isOpen = data.isOpen || false
      businessStatus.openTime = data.openTime || '08:00'
      businessStatus.closeTime = data.closeTime || '22:00'
      businessStatus.status = data.status || BUSINESS_STATUS.CLOSED
    } else {
      throw new Error(response.message || '获取营业状态失败')
    }
  } catch (error) {
    console.error('获取营业状态失败:', error)
    ElMessage.error(error.message || '获取营业状态失败')
  }
}

// 获取服务表现数据
const getPerformanceInfo = async () => {
  try {
    const response = await getPerformanceData()
    if (response.code === 200) {
      const data = response.data
      performance.rating = data.rating || 0
      performance.responseTime = data.responseTime || 0
      performance.refundRate = data.refundRate || 0
      performance.badReviewRate = data.badReviewRate || 0
    } else {
      throw new Error(response.message || '获取服务表现数据失败')
    }
  } catch (error) {
    console.error('获取服务表现数据失败:', error)
    ElMessage.error(error.message || '获取服务表现数据失败')
  }
}

// 获取账户余额数据
const getAccountBalanceData = async () => {
  try {
    const response = await getAccountBalance()
    if (response.code === 200) {
      accountBalance.value = response.data.balance || 0
    } else {
      throw new Error(response.message || '获取账户余额失败')
    }
  } catch (error) {
    console.error('获取账户余额失败:', error)
    ElMessage.error(error.message || '获取账户余额失败')
  }
}

// 获取推广统计数据
const getPromotionStatsData = async () => {
  try {
    const response = await getPromotionStats()
    if (response.code === 200) {
      const data = response.data
      promotionStats.currentExposure = data.currentExposure || 0
      promotionStats.totalExposure = data.totalExposure || 0
      promotionStats.orderIncrease = data.orderIncrease || 0
      promotionStats.consultIncrease = data.consultIncrease || 0
      promotionStats.avgRating = data.avgRating || 0
      promotionStats.exposureLevel = data.exposureLevel || 'low'
      promotionStats.needsApproval = data.needsApproval || false
      promotionStats.autoAdjusting = data.autoAdjusting || false
    } else {
      throw new Error(response.message || '获取推广统计失败')
    }
  } catch (error) {
    console.error('获取推广统计失败:', error)
    ElMessage.error(error.message || '获取推广统计失败')
  }
}

// 获取推广方案数据
const getPromotionPlansData = async () => {
  try {
    const response = await getPromotionPlans()
    if (response.code === 200) {
      // 确保数据是数组格式，并且每个项目都有必要的属性
      const plans = response.data || []
      promotionPlans.value = Array.isArray(plans) ? plans.map(plan => ({
        id: plan.id || Date.now() + Math.random(),
        name: plan.name || '未知方案',
        price: plan.price || 0,
        unit: plan.unit || '天',
        description: plan.description || '暂无描述',
        isActive: plan.isActive || false,
        purchasing: false
      })) : []
    } else {
      throw new Error(response.message || '获取推广方案失败')
    }
  } catch (error) {
    console.error('获取推广方案失败:', error)
    ElMessage.error(error.message || '获取推广方案失败')
    // 确保设置为空数组而不是null
    promotionPlans.value = []
  }
}

// 获取风控提醒数据
const getRiskAlertsData = async () => {
  try {
    const response = await getRiskAlerts()
    if (response.code === 200) {
      riskAlerts.value = response.data || []
    } else {
      throw new Error(response.message || '获取风控提醒失败')
    }
  } catch (error) {
    console.error('获取风控提醒失败:', error)
    ElMessage.error(error.message || '获取风控提醒失败')
    riskAlerts.value = []
  }
}

// 方法
const formatMoney = (amount) => {
  return (amount || 0).toLocaleString()
}

const toggleBusinessStatus = async () => {
  try {
    const action = businessStatus.isOpen ? '停止营业' : '开始营业'
    await ElMessageBox.confirm(
      `确认${action}？${businessStatus.isOpen ? '停止后将不再接收新订单' : '开始后将正常接收订单'}`,
      '营业状态',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    statusChanging.value = true

    const newStatus = businessStatus.isOpen ? BUSINESS_STATUS.CLOSED : BUSINESS_STATUS.OPEN
    const response = await updateBusinessStatus(newStatus)

    if (response.code === 200) {
      businessStatus.isOpen = !businessStatus.isOpen
      businessStatus.status = newStatus
      ElMessage.success(`已${action}`)

      // 刷新相关数据
      await getBusinessStatusData()
    } else {
      throw new Error(response.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换营业状态失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    statusChanging.value = false
  }
}

const getScoreClass = (score) => {
  if (score >= 4.5) return 'excellent'
  if (score >= 4.0) return 'good'
  if (score >= 3.5) return 'average'
  return 'poor'
}

const getResponseClass = (time) => {
  if (time <= 2) return 'excellent'
  if (time <= 5) return 'good'
  if (time <= 10) return 'average'
  return 'poor'
}

const getRefundClass = (rate) => {
  if (rate <= 1) return 'excellent'
  if (rate <= 3) return 'good'
  if (rate <= 5) return 'average'
  return 'poor'
}

const getBadReviewClass = (rate) => {
  if (rate <= 1) return 'excellent'
  if (rate <= 3) return 'good'
  if (rate <= 5) return 'average'
  return 'poor'
}

const getExposureLevelType = (level) => {
  const typeMap = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'super': 'success'
  }
  return typeMap[level] || 'info'
}

const getExposureLevelText = (level) => {
  const textMap = {
    'low': '低曝光',
    'medium': '中等曝光',
    'high': '高曝光',
    'super': '超级曝光'
  }
  return textMap[level] || '未知'
}

const toggleAutoAdjustmentSetting = async (value) => {
  try {
    const response = await toggleAutoAdjustment(value)
    if (response.code === 200) {
      promotionStats.autoAdjusting = value
      if (value) {
        ElMessage.success('智能曝光调节已开启，系统将根据反馈数据自动优化')
        // 开始智能调节
        startAutoAdjustment()
      } else {
        ElMessage.info('智能曝光调节已关闭')
      }
    } else {
      throw new Error(response.message || '设置失败')
    }
  } catch (error) {
    console.error('切换自动调节失败:', error)
    ElMessage.error(error.message || '设置失败')
    // 恢复原状态
    promotionStats.autoAdjusting = !value
  }
}

const startAutoAdjustment = () => {
  // 模拟智能调节过程
  setInterval(() => {
    if (promotionStats.autoAdjusting) {
      // 根据订单增长、咨询增长、评分等调节曝光
      adjustExposureBasedOnFeedback()
    }
  }, 30000) // 每30秒调节一次
}

const adjustExposureBasedOnFeedback = () => {
  const { orderIncrease, consultIncrease, avgRating } = promotionStats

  // 计算调节因子
  let adjustmentFactor = 1

  // 订单增长影响 (权重40%)
  if (orderIncrease > 20) adjustmentFactor += 0.3
  else if (orderIncrease > 10) adjustmentFactor += 0.1
  else if (orderIncrease < 5) adjustmentFactor -= 0.2

  // 咨询增长影响 (权重30%)
  if (consultIncrease > 40) adjustmentFactor += 0.2
  else if (consultIncrease > 20) adjustmentFactor += 0.1
  else if (consultIncrease < 10) adjustmentFactor -= 0.1

  // 评分影响 (权重30%)
  if (avgRating >= 4.8) adjustmentFactor += 0.2
  else if (avgRating >= 4.5) adjustmentFactor += 0.1
  else if (avgRating < 4.0) adjustmentFactor -= 0.3

  // 调节曝光量
  const newExposure = Math.round(promotionStats.currentExposure * adjustmentFactor)
  promotionStats.currentExposure = Math.max(100, Math.min(5000, newExposure))

  // 更新曝光等级
  updateExposureLevel()
}

const updateExposureLevel = () => {
  const exposure = promotionStats.currentExposure

  if (exposure < 500) {
    promotionStats.exposureLevel = 'low'
    promotionStats.needsApproval = false
  } else if (exposure < 1500) {
    promotionStats.exposureLevel = 'medium'
    promotionStats.needsApproval = false
  } else if (exposure < 3000) {
    promotionStats.exposureLevel = 'high'
    promotionStats.needsApproval = false
  } else {
    promotionStats.exposureLevel = 'super'
    promotionStats.needsApproval = true
  }
}

const handlePurchasePromotion = async (plan) => {
  try {
    let confirmMessage = `确认开启${plan.name}？费用：¥${plan.price}/${plan.unit}`

    if (plan.name === '新品极速推广') {
      confirmMessage += '\n\n新品将在3小时内获得大量曝光，之后根据反馈数据智能调节'
    }

    await ElMessageBox.confirm(
      confirmMessage,
      '开启推广',
      {
        confirmButtonText: '确认开启',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 检查账户余额是否足够
    if (accountBalance.value < plan.price) {
      ElMessageBox.confirm(
        `账户余额不足，当前余额：¥${accountBalance.value.toFixed(2)}，需要：¥${plan.price}。是否前往充值？`,
        '余额不足',
        {
          confirmButtonText: '前往充值',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        showRechargeDialog()
      }).catch(() => {
        // 用户取消
      })
      return
    }

    plan.purchasing = true

    const response = await purchasePromotion(plan.id, {
      duration: 1, // 购买1小时
      autoRenew: false
    })

    if (response.code === 200) {
      // 更新账户余额
      await getAccountBalanceData()

      // 刷新推广数据
      await getPromotionPlansData()
      await getPromotionStatsData()

      // 特殊处理新品推广
      if (plan.name === '新品极速推广') {
        startNewProductPromotion()
      }

      ElMessage.success(`${plan.name}已开启，开始智能推广`)
    } else {
      throw new Error(response.message || '购买推广失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('购买推广失败:', error)
      ElMessage.error(error.message || '购买推广失败')
    }
  } finally {
    plan.purchasing = false
  }
}

const startNewProductPromotion = () => {
  // 新品3小时极速推广
  promotionStats.currentExposure = 3500 // 高曝光量
  promotionStats.exposureLevel = 'super'

  ElMessage.success('新品极速推广已启动，3小时内将获得大量曝光')

  // 3小时后根据反馈调节
  setTimeout(() => {
    ElMessage.info('新品推广3小时期结束，开始根据反馈数据智能调节曝光')
    promotionStats.autoAdjusting = true
    adjustExposureBasedOnFeedback()
  }, 3 * 60 * 60 * 1000) // 3小时
}

const handlePromotionChange = (planId) => {
  console.log('选择推广方案:', planId)
}

const isPromotionActive = (planId) => {
  if (!planId) return false
  const plan = promotionPlans.value.find(p => p.id === planId)
  return plan?.isActive || false
}

const activateSelectedPromotion = () => {
  if (!selectedPromotion.value) return
  const plan = promotionPlans.value.find(p => p.id === selectedPromotion.value)
  if (plan) {
    handlePurchasePromotion(plan)
  }
}

const showRechargeDialog = () => {
  // 显示充值对话框
  rechargeDialogVisible.value = true
}

const processRecharge = async () => {
  try {
    // 验证充值金额
    if (rechargeForm.amount < 1) {
      ElMessage.error('充值金额不能少于1元')
      return
    }

    if (rechargeForm.amount > 50000) {
      ElMessage.error('单次充值金额不能超过50,000元')
      return
    }

    rechargeProcessing.value = true

    const response = await rechargeAccount({
      amount: rechargeForm.amount,
      paymentMethod: rechargeForm.paymentMethod,
      remark: '营业管理页面充值'
    })

    if (response.code === 200) {
      // 保存订单和支付信息
      currentRechargeOrder.value = response.data
      rechargePaymentInfo.value = response.data.paymentInfo

      // 计算剩余时间
      const expireTime = new Date(response.data.expireTime).getTime()
      const now = new Date().getTime()
      rechargeRemainingTime.value = Math.max(0, Math.floor((expireTime - now) / 1000))

      // 切换到支付页面
      paymentStep.value = 'payment'

      // 开始倒计时
      startRechargePaymentTimer()

      ElMessage.success('充值订单创建成功，请完成支付')
      ElMessage.info('请在第三方支付平台完成支付，支付完成后点击"刷新状态"查看结果')
    } else if (response.code === 403) {
      // 需要绑定银行卡或身份证认证
      if (response.data?.requireBankCard) {
        ElMessageBox.confirm(
          '充值功能需要先绑定银行卡，是否前往绑定？',
          '需要绑定银行卡',
          {
            confirmButtonText: '前往绑定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          router.push('/main/settings/bankcard')
        }).catch(() => {
          // 用户取消
        })
      } else if (response.data?.requireIdCard) {
        ElMessageBox.confirm(
          '充值功能需要先完成身份证实名认证，是否前往认证？',
          '需要身份证认证',
          {
            confirmButtonText: '前往认证',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          router.push('/main/settings/bankcard')
        }).catch(() => {
          // 用户取消
        })
      } else {
        ElMessage.error(response.message || '充值失败')
      }
    } else {
      throw new Error(response.message || '创建充值订单失败')
    }
  } catch (error) {
    console.error('创建充值订单失败:', error)
    ElMessage.error(error.message || '创建充值订单失败，请重试')
  } finally {
    rechargeProcessing.value = false
  }
}

const viewTransactions = () => {
  ElMessage.info('跳转到交易记录页面')
}

// 支付相关函数
const resetRechargeForm = () => {
  paymentStep.value = 'form'
  currentRechargeOrder.value = null
  rechargePaymentInfo.value = null
  checkingRechargePayment.value = false
  rechargeRemainingTime.value = 0

  if (rechargePaymentTimer.value) {
    clearInterval(rechargePaymentTimer.value)
    rechargePaymentTimer.value = null
  }

  rechargeForm.amount = 100
  rechargeForm.amountType = 'quick'
  rechargeForm.paymentMethod = 'wechat'
}

const startRechargePaymentTimer = () => {
  if (rechargePaymentTimer.value) {
    clearInterval(rechargePaymentTimer.value)
  }

  rechargePaymentTimer.value = setInterval(() => {
    if (rechargeRemainingTime.value > 0) {
      rechargeRemainingTime.value--
    } else {
      clearInterval(rechargePaymentTimer.value)
      ElMessage.warning('支付已超时，请重新发起充值')
      cancelRechargePayment()
    }
  }, 1000)
}

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const generateQRCode = (content) => {
  return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(content)}`
}

const openRechargeBank = () => {
  if (rechargePaymentInfo.value?.payUrl) {
    window.open(rechargePaymentInfo.value.payUrl, '_blank')
  } else {
    ElMessage.error('银行支付链接无效')
  }
}

const refreshRechargePaymentStatus = async () => {
  if (!currentRechargeOrder.value) {
    ElMessage.error('订单信息不存在')
    return
  }

  checkingRechargePayment.value = true

  try {
    const response = await fetch(currentRechargeOrder.value.checkUrl)
    const result = await response.json()

    if (result.code === 200) {
      const status = result.data.status

      if (status === 'paid') {
        // 支付成功 - 进行二次验证
        clearInterval(rechargePaymentTimer.value)

        // 验证订单时间（防止过快确认）
        const orderTime = new Date(currentRechargeOrder.value.createTime).getTime()
        const now = new Date().getTime()

        if (now - orderTime < 10000) { // 10秒内完成支付可能是虚假的
          ElMessage.warning('支付确认过快，请稍后再试')
          checkingRechargePayment.value = false
          return
        }

        // 刷新账户余额进行验证
        const oldBalance = accountBalance.value
        await getAccountBalanceData()
        const newBalance = accountBalance.value

        // 验证余额是否真实增加
        if (newBalance >= oldBalance + currentRechargeOrder.value.amount) {
          ElMessage.success('支付成功！充值已到账')

          // 关闭对话框并重置状态
          rechargeDialogVisible.value = false
          resetRechargeForm()
        } else {
          ElMessage.error('支付状态异常，余额未正确更新，请联系客服')
          cancelRechargePayment()
        }
      } else if (status === 'failed') {
        ElMessage.error(`支付失败：${result.data.failReason || '未知原因'}`)
        cancelRechargePayment()
      } else if (status === 'expired') {
        ElMessage.warning('支付已超时，请重新发起充值')
        cancelRechargePayment()
      } else {
        ElMessage.info('支付处理中，请在第三方支付平台完成支付后再次刷新')
      }
    } else if (result.code === 404) {
      ElMessage.error('订单不存在或已失效')
      cancelRechargePayment()
    } else {
      throw new Error(result.message || '查询支付状态失败')
    }
  } catch (error) {
    console.error('查询支付状态失败:', error)
    ElMessage.error('查询支付状态失败，请检查网络连接后重试')
  } finally {
    checkingRechargePayment.value = false
  }
}

const cancelRechargePayment = () => {
  clearInterval(rechargePaymentTimer.value)
  rechargeDialogVisible.value = false
  resetRechargeForm()
  ElMessage.info('已取消支付')
}

// 页面初始化
onMounted(async () => {
  console.log('商家营业管理页面已加载')

  try {
    await Promise.all([
      getBusinessStatusData(),
      getPerformanceInfo(),
      getAccountBalanceData(),
      getPromotionStatsData(),
      getPromotionPlansData(),
      getRiskAlertsData()
    ])
    console.log('✅ 营业管理数据加载完成')
  } catch (error) {
    console.error('❌ 营业管理数据加载失败:', error)
    ElMessage.error('页面数据加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.business-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 营业状态区域 */
.status-section {
  margin-bottom: 20px;
}

.status-card,
.performance-card,
.promotion-selector-card {
  border-radius: 12px;
  border: none;
  height: 100%;
}

.status-card.compact,
.performance-card.compact,
.promotion-selector-card.compact {
  height: auto;
}

.status-content {
  padding: 15px 0;
}

.status-display {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 28px;
  color: white;
}

.status-icon.open {
  background: linear-gradient(135deg, #10b981, #059669);
}

.status-icon.closed {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.status-info h3,
.status-info h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
}

.status-info p {
  margin: 0;
  color: #6b7280;
  font-size: 13px;
}

.status-actions {
  text-align: center;
}

.performance-content {
  padding: 20px 0;
}

.performance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.performance-item .label {
  font-size: 14px;
  color: #6b7280;
}

.performance-item .value {
  font-size: 16px;
  font-weight: bold;
}

.performance-item .value.excellent {
  color: #10b981;
}

.performance-item .value.good {
  color: #3b82f6;
}

.performance-item .value.average {
  color: #f59e0b;
}

.performance-item .value.poor {
  color: #ef4444;
}

/* 推广区域 */
.promotion-section {
  margin-bottom: 20px;
}

.promotion-card,
.balance-card,
.risk-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.promotion-plans {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.plan-item {
  flex: 1;
  min-width: 200px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  background: white;
  transition: all 0.3s ease;
}

.plan-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
}

.plan-item.active {
  border-color: #10b981;
  background: linear-gradient(135deg, #ecfdf5, #f0fdf4);
}

.plan-header {
  text-align: center;
  margin-bottom: 20px;
}

.plan-header h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
}

.plan-price .price {
  font-size: 24px;
  font-weight: bold;
  color: #059669;
}

.plan-price .unit {
  font-size: 14px;
  color: #6b7280;
}

.plan-description {
  margin-bottom: 15px;
}

.plan-description p {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.plan-features {
  margin-bottom: 20px;
}

/* 推广数据统计 */
.promotion-stats {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.promotion-stats .stat-item {
  text-align: center;
}

.promotion-stats .stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.promotion-stats .stat-label {
  font-size: 12px;
  color: #6b7280;
}

/* 智能调节 */
.auto-adjustment {
  margin-bottom: 20px;
  padding: 15px;
  background: #eff6ff;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.adjustment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
  color: #1f2937;
}

.adjustment-info {
  margin-top: 10px;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #374151;
}

.feature-icon {
  color: #10b981;
  margin-right: 8px;
  font-size: 16px;
}

.plan-actions {
  text-align: center;
}

/* 余额卡片 */
.balance-content {
  text-align: center;
  padding: 20px 0;
}

.balance-display {
  margin-bottom: 20px;
}

.balance-amount {
  font-size: 32px;
  font-weight: bold;
  color: #059669;
  margin-bottom: 8px;
}

.balance-label {
  font-size: 14px;
  color: #6b7280;
}

.balance-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

/* 风控卡片 */
.risk-content {
  padding: 10px 0;
}

.risk-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  padding: 12px;
  background: #fef2f2;
  border-radius: 8px;
  border-left: 4px solid #ef4444;
}

.risk-icon {
  margin-right: 12px;
  margin-top: 2px;
  font-size: 18px;
}

.risk-icon.warning {
  color: #f59e0b;
}

.risk-icon.danger {
  color: #ef4444;
}

.risk-info {
  flex: 1;
}

.risk-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.risk-desc {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

/* 充值对话框 */
.recharge-content {
  padding: 20px 0;
}

.current-balance {
  text-align: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
}

.current-balance .balance {
  font-size: 20px;
  font-weight: bold;
  color: #059669;
  margin-left: 8px;
}

.quick-amounts {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.recharge-summary {
  margin-top: 20px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item:last-child {
  margin-bottom: 0;
  font-weight: bold;
  font-size: 16px;
}

.summary-item .amount {
  color: #059669;
  font-weight: bold;
}

/* 推广选择器 */
.promotion-selector {
  padding: 10px 0;
}

.promotion-selector .el-select {
  margin-bottom: 12px;
}

/* 自定义充值提示 */
.custom-tips {
  margin-top: 8px;
  padding: 8px;
  background: #f8fafc;
  border-radius: 4px;
  border-left: 3px solid #3b82f6;
}

.custom-tips p {
  margin: 2px 0;
  font-size: 12px;
  color: #6b7280;
}

.quick-amounts {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-amounts .el-button {
  flex: 1;
  min-width: 80px;
}

/* 支付页面样式 */
.payment-section {
  padding: 20px 0;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.payment-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #1f2937;
}

.payment-info .amount {
  margin: 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #059669;
}

.payment-info .order-id {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #6b7280;
}

.payment-timer {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  font-weight: 500;
  font-size: 16px;
}

.payment-content {
  margin-bottom: 20px;
}

.payment-method-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.qr-section {
  display: flex;
  gap: 30px;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.qr-instructions {
  flex: 1;
  max-width: 300px;
}

.qr-instructions p {
  margin: 8px 0;
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
}

.bank-section {
  text-align: center;
  padding: 20px;
}

.bank-instruction {
  margin: 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.payment-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.payment-status {
  text-align: center;
  padding: 40px 20px;
}

.payment-status .el-icon {
  font-size: 32px;
  color: #3b82f6;
  margin-bottom: 12px;
}

.payment-status p {
  margin: 0;
  color: #6b7280;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .business-management {
    padding: 10px;
  }

  .status-section .el-col,
  .promotion-section .el-col {
    margin-bottom: 16px;
  }

  .promotion-plans {
    flex-direction: column;
  }

  .plan-item {
    min-width: auto;
  }

  .balance-actions {
    flex-direction: column;
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 12px 12px 0 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 10px;
}
</style>
